package org.autumn.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class FastJsonTest {
    @Test
    public void test1(){
        Student student = new Student().setName("mk").setAddress("beijing");
        // {"address":"beijing","name":"mk"}
        System.out.println(JSON.toJSONString(student));


    }


    @Test
    public void test2(){
        ArrayList<Object> list = new ArrayList<>();
        // [{"address":"beijing","name":"mk"},{"address":"beijing","name":"mk"}]
        list.add(new Student().setName("mk").setAddress("beijing"));
        list.add(new Student().setName("mk").setAddress("beijing"));
        System.out.println(JSON.toJSONString(list));
    }


    @Test
    public void test3(){
        HashMap<String, Student> map = new HashMap<>();
        // {"1":{"address":"beijing","name":"mk"},"2":{"address":"beijing","name":"mk"}}
        map.put("1",new Student().setName("mk").setAddress("beijing"));
        map.put("2",new Student().setName("mk").setAddress("beijing"));
        System.out.println(JSON.toJSONString(map));
    }

    @Test
    public void test4(){
        String student = "{\"address\":\"beijing\",\"name\":\"mk\"}";
        JSONObject jsonObject = JSON.parseObject(student);

        System.out.println(jsonObject.getString("address"));

        Student student1 = JSON.parseObject(student, Student.class);

        System.out.println(student1);

    }

    @Test
    public void test5(){
        String students = "[{\"address\":\"beijing\",\"name\":\"mk\"},{\"address\":\"beijing\",\"name\":\"mk\"}]";

        List<Student> list = JSON.parseArray(students, Student.class);

        list.forEach(System.out::println);
    }


    @Test
    public void test6(){
        String students = "{\"1\":{\"address\":\"beijing\",\"name\":\"mk\"},\"2\":{\"address\":\"beijing\",\"name\":\"mk\"}}";


        Map<String, Student> map = JSON.parseObject(students, new TypeReference<Map<String, Student>>() {});

        System.out.println(map);
    }
}

@Data
@Accessors(chain = true)
class Student{
    String name;
    String address;
}